package com.itranswarp.weibo.api;

import java.io.IOException;
import java.lang.reflect.Proxy;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * API client builder.
 *
 * @author Michael Liao (askxuefeng@gmail.com)
 */
public class ApiClientBuilder {

	String appKey;
	String appSecret;
	String apiPrefix;
	String authPrefix;

	public ApiClientBuilder(String appKey, String appSecret) {
		this(appKey, appSecret, "api.weibo.com", 2);
	}

	public ApiClientBuilder(String appKey, String appSecret, String apiDomain, int apiVersion) {
		this.appKey = appKey;
		this.appSecret = appSecret;
		this.apiPrefix = "https://" + apiDomain + "/" + apiVersion + "/";
		this.authPrefix = "https://" + apiDomain + "/oauth2/";
	}

	public final String getAuthUrl(String callbackUrl) throws IOException {
		return authPrefix + "authorize?response_type=code&client_id="
				+ URLEncoder.encode(appKey, "UTF-8") + "&redirect_uri="
				+ URLEncoder.encode(callbackUrl, "UTF-8");
	}

	public final AccessToken requestAccessToken(String code, String callbackUrl) throws IOException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("client_id", appKey);
		params.put("client_secret", appSecret);
		params.put("redirect_uri", callbackUrl);
		params.put("code", code);
		params.put("grant_type", "authorization_code");
		JsonObject jo = Utils.httpRequest(HttpMethod.POST, authPrefix + "access_token", null, params, false);
		Utils.checkError(jo);
		System.out.println(jo);
		String token = jo.get("access_token");
		Long expiresIn = jo.get("expires_in");
		return new AccessToken(token, expiresIn);
	}

	public final ApiClient create(AccessToken accessToken) {
		return (ApiClient) Proxy.newProxyInstance(
				ApiClient.class.getClassLoader(),
	            new Class[] { ApiClient.class },
	            new ApiInvocationHandler(apiPrefix, accessToken));
	}

}
